<script setup lang="ts">
import router from '@/router'
import { useUserStore } from '@/stores'
import defaultAvatar from '@/assets/images/default-avatar.svg'
import { computed, onMounted, ref } from 'vue'
import request from '@/utils/request'
import { storage } from '../../stores/mystore/auth'

// onMounted(() => {
//   console.log("进入了我的页面")
//   const userInfo = storage.get('userInfo','local')
//   console.log("USERINFO",userInfo)
//   if (userInfo) {
//     // @ts-ignore
//     // userdata.across_num = userInfo.across_num
//     // @ts-ignore
//     userdata.avatarBase64 = userInfo.avatarBase64
//     // @ts-ignore
//     userdata.avatar_url = userInfo.avatar_url
//     // @ts-ignore
//     userdata.create_tm = userInfo.create_tm
//     // @ts-ignore
//     userdata.email = userInfo.email
//     // @ts-ignore
//     // userdata.encrypt_pwd = userInfo.encrypt_pwd
//     // @ts-ignore
//     userdata.encryption_algorithm = userInfo.encryption_algorithm
//     // @ts-ignore
//     userdata.freeze_ornnt = userInfo.freeze_ornnt
//     // @ts-ignore
//     userdata.id = userInfo.id
//     // @ts-ignore
//     userdata.role_num = userInfo.role_num
//     // @ts-ignore
//     userdata.tel_num = userInfo.tel_num
//     // @ts-ignore
//     userdata.update_tm = userInfo.update_tm
//     // @ts-ignore
//     userdata.username = userInfo.username
//     // @ts-ignore
//     userdata.wechat_abt = userInfo.wechat_abt
//     // @ts-ignore
//     userdata.account_money = userInfo.account_money
//     // @ts-ignore
//     userdata.b_account = userInfo.b_account
//   }

// })

// 首页设置和示例功能相关
import type { PickerColumn } from 'vant'
import { languageColumns, locale } from '@/utils/i18n'

const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const isLogin = computed(() => !!userdata.id)

// 添加下拉刷新状态变量
const refreshing = ref(false)

// 提取用户信息获取逻辑为单独的函数
async function fetchUserInfo() {
  console.log('获取用户信息')
  const userInfo = storage.get('userInfo', 'local')
  if (userInfo) {
    // @ts-ignore
    userdata.avatarBase64 = userInfo.avatarBase64
    // @ts-ignore
    userdata.avatar_url = userInfo.avatar_url
    // @ts-ignore
    userdata.create_tm = userInfo.create_tm
    // @ts-ignore
    userdata.email = userInfo.email
    // @ts-ignore
    userdata.encryption_algorithm = userInfo.encryption_algorithm
    // @ts-ignore
    userdata.freeze_ornnt = userInfo.freeze_ornnt
    // @ts-ignore
    userdata.id = userInfo.id
    // @ts-ignore
    userdata.role_num = userInfo.role_num
    // @ts-ignore
    userdata.tel_num = userInfo.tel_num
    // @ts-ignore
    userdata.update_tm = userInfo.update_tm
    // @ts-ignore
    userdata.username = userInfo.username
    // @ts-ignore
    userdata.wechat_abt = userInfo.wechat_abt
    // @ts-ignore
    userdata.account_money = userInfo.account_money
    // @ts-ignore
    userdata.b_account = userInfo.b_account
  }
}

// 刷新处理函数
async function onRefresh() {
  console.log('下拉刷新触发')

  // 模拟API请求延迟
  await new Promise(resolve => setTimeout(resolve, 800))

  try {
    // 重新获取用户信息
    const res = await request.post('/dragon/getuserInfo', {
      uName: userdata.username,
      uCellphone: userdata.tel_num,
    })
    console.log('fetchUserInfo', res.data)
    storage.set('userInfo', res.data, {
      type: 'local',
      expires: 1, // 一天过期
      encrypt: false, // 是否加密
    })
    await fetchUserInfo()
    console.log('用户信息刷新成功')

    // <a href="http://king.dragons.org.cn"> Deagons </a>
    // <span> © 2024 | </span>
    // <a href="https://beian.miit.gov.cn/"> 沪ICP备2024089484号 </a>

    // 显示轻提示（可选）
    // showToast('数据已更新')
  }
  catch (error) {
    console.error('刷新失败:', error)
    // 显示错误提示（可选）
    // showFailToast('刷新失败，请重试')
  }
  finally {
    // 结束刷新状态
    refreshing.value = false
  }
}

function login() {
  if (isLogin.value)
    return
  router.push({ name: 'login', query: { redirect: 'profile' } })
}

function logout() {
  // 清除用户信息
  storage.remove('userInfo', 'local')
  Object.assign(userdata, {})

  // 跳转到首页
  router.replace('/')
}

// 监听router当跳转到此页面的时候查询 用户信息并更新本地存储

/**
 * 计算MySQL时间字符串距离当前时间的天数
 * @param {string} mysqlTimestamp - MySQL时间字符串 (格式: 2025-06-19T00:41:03.000+00:00)
 * @returns {number} 天数差（正数表示过去时间，负数表示未来时间）
 */
function calculateDaysFromNow(mysqlTimestamp) {
  // 1. 解析MySQL时间字符串为UTC时间
  const targetDate = new Date(mysqlTimestamp)

  // 2. 获取当前时间（精确到毫秒）
  const now = new Date()

  // 3. 计算毫秒级时间差并转换为天数
  // @ts-ignore
  const timeDiffMs = now - targetDate
  const daysDiff = timeDiffMs / (1000 * 60 * 60 * 24)

  // 4. 返回保留两位小数的结果
  return Number(daysDiff.toFixed(2)) || 0
}

const userdata = reactive({
  across_num: '',
  avatarBase64: '',
  avatar_url: '',
  create_tm: '',
  email: '',
  encrypt_pwd: '',
  encryption_algorithm: '',
  freeze_ornnt: '',
  id: '',
  role_num: '',
  tel_num: '',
  update_tm: '',
  username: '',
  wechat_abt: '',
  account_money: 0, // 余额
  b_account: 0.0000, // 余额（保留四位小数）
})

onMounted(() => {
  console.log('进入了我的页面')
  fetchUserInfo()
})

const { t } = useI18n()

const checked = computed({
  get: () => isDark.value,
  set: () => toggleDark(),
})

// const menuItems = computed(() => ([
//   { title: 'Mock 指南', route: 'mock' },
//   { title: t('menus.echartsDemo'), route: 'charts' },
//   { title: t('menus.unocssExample'), route: 'unocss' },
//   { title: t('menus.persistPiniaState'), route: 'counter' },
//   { title: t('menus.keepAlive'), route: 'keepalive' },
//   { title: t('menus.scrollCache'), route: 'scroll-cache' },
//   { title: t('menus.404Demo'), route: 'unknown' },
// ]))

const menuItems = computed(() => ([
  { title: '订单处理', route: 'mock' },
  // { title: t('menus.echartsDemo'), route: 'charts' },
  // { title: t('menus.unocssExample'), route: 'unocss' },
  // { title: t('menus.persistPiniaState'), route: 'counter' },
  // { title: t('menus.keepAlive'), route: 'keepalive' },
  // { title: t('menus.scrollCache'), route: 'scroll-cache' },
  // { title: t('menus.404Demo'), route: 'unknown' },
]))

const showLanguagePicker = ref(false)
const languageValues = ref<Array<string>>([locale.value])
const language = computed(() => languageColumns.find(l => l.value === locale.value).text)

function onLanguageConfirm(event: { selectedOptions: PickerColumn }) {
  locale.value = event.selectedOptions[0].value as string
  showLanguagePicker.value = false
}

// 新增跳转方法
function goWallet() {
  router.push('/wallet')
}
function goTrade() {
  router.push('/trade')
}
function goInfo() {
  router.push('/profile/info')
}
</script>

<template>
  <!-- 添加下拉刷新容器 -->
  <van-pull-refresh
    v-model="refreshing"
    pulling-text="下拉刷新"
    loosing-text="释放立即刷新"
    success-text="刷新成功"
    success-duration="800"
    @refresh="onRefresh"
  >
    <div>
      <VanCellGroup :inset="true">
        <van-cell center :is-link="!isLogin" @click="login">
          <template #title>
            <!-- <van-image
              v-if="isLogin"
              :src="userdata.avatarBase64 || userdata.avatar_url"
              round
              class="h-56 w-56"
            /> -->
            <!-- 添加边框的效果 -->
            <div v-if="isLogin" class="avatar-glow">
              <van-image
                v-if="isLogin"
                :src="userdata.avatarBase64 || userdata.avatar_url"
                round
                class="h-56 w-56"
              />
            </div>
          </template>
          <template #value>
            <span v-if="isLogin">{{ userdata.username }}</span>
            <span v-else>登录</span>
          </template>
        </van-cell>
      </VanCellGroup>

      <!-- 余额/注册天数卡片区域（Vant组件实现） -->
      <van-row
        v-if="isLogin"
        class="profile-stats-row"
        justify="space-between"
        align="center"
        style="margin: 16px 0 8px 0; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.03);"
      >
        <van-col span="12" class="profile-stats-col">
          <div class="profile-stats-value">
            {{ userdata.b_account ?? '0.00' }}<span class="profile-stats-unit">元</span>
          </div>
          <div class="profile-stats-label">
            余额
          </div>
        </van-col>
        <van-col span="12" class="profile-stats-col" style="border-left: 1px solid #f2f3f5;">
          <div class="profile-stats-value">
            {{ calculateDaysFromNow(userdata.create_tm) ?? '0' }}<span class="profile-stats-unit">天</span>
          </div>
          <div class="profile-stats-label">
            注册天数
          </div>
        </van-col>
      </van-row>

      <!-- 新增：钱包、交易明细、我的信息列表 -->
      <van-cell-group :inset="true" style="margin-bottom: 16px;">
        <!-- <van-cell
          title="钱包"
          is-link
          @click="goWallet"
        >
          <template #icon>
            <div class="i-carbon:money-bag text-gray-400 mr-5 self-center" />
          </template>
        </van-cell>
        <van-cell
          title="交易明细"
          is-link
          @click="goTrade"
        >
          <template #icon>
            <div class="i-carbon:document text-gray-400 mr-5 self-center" />
          </template>
        </van-cell> -->
        <!-- <van-cell
          title="我的信息"
          is-link
          @click="goInfo"
        >
          <template #icon>
            <div class="i-carbon:user text-gray-400 mr-5 self-center" />
          </template>
        </van-cell> -->
      </van-cell-group>

      <VanCellGroup :inset="true" class="!mt-16">
        <van-cell :title="$t('profile.settings')" icon="setting-o" is-link to="/settings">
          <template #icon>
            <div class="i-carbon:settings text-gray-400 mr-5 self-center" />
          </template>
        </van-cell>
        <!-- <van-cell :title="$t('profile.docs')" is-link url="https://easy-temps.github.io/easy-docs/vue3-vant-mobile/">
          <template #icon>
            <div class="i-carbon:doc text-gray-400 mr-5 self-center" />
          </template>
        </van-cell> -->
      </VanCellGroup>
      <van-cell-group :title="$t('menus.basicSettings')" :border="false" :inset="true">
        <van-cell center :title="$t('menus.darkMode')">
          <template #right-icon>
            <van-switch
              v-model="checked"
              size="20px"
              aria-label="on/off Dark Mode"
            />
          </template>
        </van-cell>
        <van-cell
          is-link
          :title="$t('menus.language')"
          :value="language"
          @click="showLanguagePicker = true"
        />
      </van-cell-group>

      <!-- <van-cell-group :title="$t('menus.exampleComponents')" :border="false" :inset="true">
        <template v-for="item in menuItems" :key="item.route">
          <van-cell :title="item.title" :to="item.route" is-link />
        </template>
      </van-cell-group> -->

      <van-popup v-model:show="showLanguagePicker" position="bottom">
        <van-picker
          v-model="languageValues"
          :columns="languageColumns"
          @confirm="onLanguageConfirm"
          @cancel="showLanguagePicker = false"
        />
      </van-popup>
    </div>
  </van-pull-refresh>

  <div class="order-actions">
    <van-button v-if="isLogin" type="primary" block @click="logout">
      退出登录
    </van-button>
  </div>
</template>

<style scoped>
.profile-stats-row {
  min-height: 60px;
  padding: 0;
}
.profile-stats-col {
  text-align: center;
  padding: 12px 0 8px 0;
}
.profile-stats-value {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
  margin-bottom: 2px;
}
.profile-stats-unit {
  font-size: 16px;
  margin-left: 2px;
}
.profile-stats-label {
  font-size: 14px;
  color: #888;
}

.profile-root {
  background: #f7f7fa;
  min-height: 100vh;
}
.profile-top {
  display: flex;
  background: #fff;
  border-radius: 0 0 12px 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  margin-bottom: 18px;
}
.profile-top-item {
  flex: 1;
  text-align: center;
  padding: 18px 0 10px 0;
}
.profile-top-value {
  color: #ff3c3c;
  font-size: 26px;
  font-weight: bold;
  margin-bottom: 2px;
}
.profile-top-unit {
  font-size: 16px;
  color: #ff3c3c;
  margin-left: 2px;
}
.profile-top-label {
  color: #888;
  font-size: 16px;
  margin-top: 2px;
}
.profile-list {
  background: #fff;
  border-radius: 12px;
  margin: 0 0 18px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
.profile-list-item {
  display: flex;
  align-items: center;
  font-size: 20px;
  padding: 18px 18px 18px 18px;
  border-bottom: 1px solid #f2f2f2;
  color: #222;
  font-weight: 500;
}
.profile-list-item:last-child {
  border-bottom: none;
}
.profile-list-arrow {
  margin-left: auto;
  color: #bbb;
  font-size: 22px;
}
.iconfont {
  margin-right: 12px;
  font-size: 22px;
}
.profile-logout-bar {
  margin: 32px 0 18px 0;
  display: flex;
  justify-content: center;
}
.profile-logout-btn {
  width: 90%;
  height: 48px;
  background: linear-gradient(90deg, #ff7e5f, #ff3c3c);
  color: #fff;
  font-size: 22px;
  font-weight: bold;
  border: none;
  border-radius: 24px;
  cursor: pointer;
}

.order-actions {
  margin: 24px 16px 0 16px;
}

/* -------------------------------头像的边框效果 */
/* 核心流光容器 */
.avatar-glow {
  position: relative;
  display: inline-block;
  border-radius: 50%; /* 圆形 */
  padding: 10px; /* 控制光带宽度 */
}

/* 流光动画层 */
.avatar-glow::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    45deg,
    #ff0000,
    #ff7300,
    #fffb00,
    /* 红→橙→黄 */ #48ff00,
    #00ffd5,
    #002bff,
    /* 绿→青→蓝 */ #7a00ff,
    #ff00c8,
    #ff0000 /* 紫→粉→红 */
  );
  background-size: 400% 400%; /* 扩大背景制造流动感 */
  border-radius: 50%;
  z-index: 0;
  animation: glow-animation 3s linear infinite;
  filter: blur(5px); /* 光晕扩散效果 */
}

/* 遮罩层（仅显示边缘） */
.avatar-glow::after {
  content: '';
  position: absolute;
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  background: #000000;
  border-radius: 50%;
  z-index: 1;
}

/* 头像置于最上层 */
.van-image {
  position: relative;
  z-index: 2;
}

/* 流光动画 */
@keyframes glow-animation {
  0% {
    background-position: 0% 50%;
  }
  100% {
    background-position: 100% 50%;
  }
}
/* -------------------------------头像的边框效果 */
</style>

<route lang="json5">
{
  name: 'profile',
  meta: {
    title: '个人中心',
    i18n: 'menus.profile'
  },
}
</route>
